package sms.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.MD5Utils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import sms.AbstractSmsApi;
import sms.model.Result;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xiao.lai on 2015/10/19.
 */
public class JuxinSms extends AbstractSmsApi {

    private static final Log log = LogFactory.getLog(JuxinSms.class);

    private static String Url = "http://api.app2e.com/smsBigSend.api.php";
    private static String userName = "qckj";     //
    private static String password = "HcthHm8Q";


    private static Map<Byte,String> messageTemplate = new HashMap<Byte, String>();
    static{
        messageTemplate.put(MESSAGE_TEMPLATE_USER_BIND_PHONE,     "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REGISTER,       "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_LOGIN ,         "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND,         "您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_PASSWPRD_RECOVERY,"您正在找回密码,您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_BINDING_YES,"您正在绑定支付账户,您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_BINDING_NO,"您正在解绑支付账户,您的验证码是：【变量】，【变量】分钟内有效。");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_EXAMINE_YES,"恭喜您，您申请的【变量】达人已通过，请登录百灵鸟达人版发布活动，结识更多的百灵鸟小伙伴！");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_EXAMINE_NO,"很抱歉，您申请的【变量】达人未通过，【变量】，请登陆百灵鸟达人版更改信息!");
        messageTemplate.put(MESSAGE_TEMPLATE_USER_REFUND_SMS,"您报名的【变量】活动已退款，退款金额【变量】元，1-3个工作日到账。订单号:【变量】。进入[我的活动]查看详情。");
        messageTemplate.put(MESSAGE_TEMPLATE_BATCH_REFUND_SMS,"非常抱歉！您参加的【变量】活动由于【变量】临时取消，您支付的款项和鸟蛋将会在1-3个工作日内退款至您的原支付渠道，退款到账日期以支付宝/微信支付为准， \n" +
                                                                "如有疑问，请拨打客服电话【变量】。");
    }

    @Override
    protected String getTemplateByType(Byte id) {
        return messageTemplate.get(id);
    }

    @Override
    public Result sendMsg(String phone, Byte templateId, String[] args) {
        String content = getTemplateByType(templateId);
        for(int i = 1; i <= args.length ; i++){
            content = content.replaceFirst("【变量】", args[i - 1]);
        }
        String[] phones = {phone};
        return sendMsg(phones, content);
    }


    public Result sendMsg(String[] phones, Byte templateId, String[] args) {
        String content = getTemplateByType(templateId);
        for(int i = 1; i <= args.length ; i++){
            content = content.replaceFirst("【变量】", args[i - 1]);
        }
        return sendMsg(phones, content);
    }

    private Result sendMsg(String[] phones, String content) {
        Result result = Result.returnFail(Result.SMS_SEND_FAILURE);

        try {
            //处理电话的数组为String串
            StringBuffer sb = new StringBuffer();
            for(int i = 0; i < phones.length; i++){
                sb. append(phones[i].trim()+",");
            }
            String phoneStr = sb.toString().substring(0, sb.toString().length() - 1);


            NameValuePair[] data = {//提交短信
                    new NameValuePair("username", userName),
                    new NameValuePair("pwd", MD5Utils.MD5Encode(password).toLowerCase()),
                    new NameValuePair("p", phoneStr),
                    new NameValuePair("msg", content),
                    new NameValuePair("charSetStr", "utf-8"),
                    new NameValuePair("isUrlEncode", "no"),
            };

            //postMethod.setRequestBody(data);
            String smsContent = "";
            for(NameValuePair nameValuePair : data){
                smsContent += "&"+nameValuePair.getName() + "=" + nameValuePair.getValue();
            }

            smsContent = smsContent.replaceFirst("&","");

            String responseString = HttpClientUtils.post(Url, smsContent);
            System.out.println(responseString);
           // httpClient.executeMethod(postMethod);
           // String SubmitResult = postMethod.getResponseBodyAsString();
            log.info("send to " + phones + " message SubmitResult=> " + responseString);

            //解析JsonObject
            JSONObject jsonObject = JSON.parseObject(responseString);
            String status = jsonObject.getString("status");
            Integer count = jsonObject.getInteger("count");
            Object list = jsonObject.get("list");
            switch (Integer.parseInt(status)) {
                case 100:
                    result = Result.returnSuccess(Result.SMS_SEND_SUCCESS);
                    break; //提交成功
                case 102: //号码错误
                    result = Result.returnFail(Result.INVALID_PHONE_NUMBER);
                    break;
                case 103://当日余量不足.
                    result = Result.returnFail(Result.SMS_SEND_TOO_OFTEN);
                    break;
                case 106:
                    result = Result.returnFail(Result.INVALID_PHONE_NUMBER);
                    break; //非法手机用户
                case 121:
                    result = Result.returnFail(Result.INCLUDE_SENSITIVE_WORD);
                    break; //敏感词
                default:
                    result = new Result(false, Integer.parseInt(status), "JUXIN-短信发送失败!");
                    break;
            }
            return result;

        }catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        JuxinSms sms = new JuxinSms();
        sms.sendMsg("13522985502",MESSAGE_TEMPLATE_USER_BIND_PHONE,new String[]{"3376","23","12"});
       // String[] phones = {"13552432337","18901341001","13121215933"};
        //sms.sendMsg(phones, "ddd");
    }
}
